function buildTable() {
    dwr.util.removeAllRows("searchEnginesTable");
    OpenSearchSettings.getSearchEngines(addTableRows);
}

var cellFuncs = [
        function (data) {
            return ((data.iconURL != null) ? "<img src=\"" + data.iconURL
                    + "\" height=\"16\" width=\"16\"/> &nbsp;" : "");
        },
        function(data) {
            return "<a href=\"" + data.descriptorURL + "\" target=\"_new\" title=\""
                    + data.description + "\">" + data.shortName + "</a>";
        },
        function(data) {
            return data.queryResultParseable ? "Yes" : "No";
        },
        function(data) {
            return data.authenticated ? "Yes" : "No";
        },
        function(data) {
            return data.enabled ? "Yes" : "No";
        },
        function(data) {
            return "<input type=\"button\" value=\"Edit\" onClick=\"editEngine(" + data.ID + ")\">";
        },
        function(data) {
            return (data.queryResultParseable)
                    ? "<input type=\"button\" value=\"Test\" onClick=\"testEngine(this, " + data.ID
                    + ")\" >" : "";
        },
        function(data) {
            return "<input type=\"button\" value=\"Delete\" onClick=\"deleteEngine(" + data.ID
                    + ")\">";
        }
        ];

function addEngineFromURL(f, url) {
    hideMessage();
    f.newDescriptorURL.value = "";
    displayMessage("info", "Parsing descriptor file ...");
    OpenSearchSettings.addSearchEngineFromDescriptorURL(url, {
        callback:addTableRow,
        errorHandler:function(errorString, exception) {
            displayMessage("error", "Engine addition failed:  " + errorString);
        }
    });
}

function addEngineFromForm() {
    hideMessage();
    loadEditForm(getNewEngine());
}

function addTableRow(searchEngine) {
    addTableRows([searchEngine]);
    //if auth, we need to ask the user for credentials
    if (searchEngine.authenticated) {
        displayMessage("info", "This search engine is protected.<br/>Please add credentials.");
        OpenSearchSettings.getSearchEngineByID(searchEngine.ID, loadEditForm);
    }
    else
    {
        displayMessage("success", "Search engine added successfully.");
    }

}

function addTableRows(searchEngines) {
    dwr.util.addRows("searchEnginesTable", searchEngines, cellFuncs, {
        cellCreator:function(options) {
            var td = document.createElement("td");
            if (options.cellNum == 0) {
                td.className = "jive-table-os-icon";
            }
            if (options.cellNum == 1) {
                td.className = "jive-table-os-name";
            }
            if (options.cellNum == 2) {
                td.className = "jive-table-os-inline";
            }
            if (options.cellNum == 3) {
                td.className = "jive-table-os-auth";
            }
            if (options.cellNum == 4) {
                td.className = "jive-table-os-enabled";
            }
            if (options.cellNum == 5) {
                td.className = "jive-table-os-edit";
            }
            if (options.cellNum == 6) {
                td.className = "jive-table-os-test";
            }
            if (options.cellNum == 7) {
                td.className = "jive-table-os-delete";
            }
            //var index = 255 - (options.rowIndex * 50);
            //td.style.backgroundColor = "rgb(" + index + ",255,255)";
            //td.style.fontWeight = "bold";
            return td;
        },
        escapeHtml:false
    });
}

function editEngine(engineID) {
    hideMessage();
    OpenSearchSettings.getSearchEngineByID(engineID, loadEditForm);
}

function loadEditForm(engine) {
    $("edit-search-descriptor").show();
    $("add-search-descriptor").hide();
    var f = $("edit-search-descriptor-form");
    dwr.util.setValues(engine);
    $("search-engine-enabled").checked = engine.enabled;
    updateExtFieldSelect();
}

function updateEngine(form) {
    hideMessage();
    var engine = getNewEngine();
    dwr.util.getValues(engine);
    engine.enabled = $("search-engine-enabled").checked;
    //validate engine
    if (isValidated(engine)) {
        OpenSearchSettings.saveSearchEngineAsMap(engine, {
            callback:function() {
                updateEngineCallback(engine.ID);
            },
            errorHandler:function(errorString, exception) {
                displayMessage("error", "Update failed:  " + errorString + " exception: "
                        + exception);
            }
        });
    }
}

function isValidated(engine) {
    //make sure short name is not blank
    if (trimStr(engine.shortName) == "") {
        displayMessage("error", "A name is required.");
        return false;
    }
    //make sure search URL is not blank
    if (trimStr(engine.searchURL) == "") {
        displayMessage("error", "Search URL is required.");
        return false;
    }
    //make sure external search URL is not blank
    if (trimStr(engine.externalSearchURL) == "") {
        //if HTML content type is selected, then just copy over the HTML search URL value
        if (isContentTypeHTML()) {
            engine.externalSearchURL = engine.searchURL;
        }
        else
        {
            displayMessage("error", "External search URL is required.");
            return false;
        }
    }
    //make sure query test term is not blank
    if (trimStr(engine.queryTestTerm) == "") {
        displayMessage("error", "A query test term is required.");
        return false;
    }
    //make sure description is <= 2000 chars
    if (engine.description.length > 2000) {
        displayMessage("error", "Description is limited to 2000 characters.");
        return false;
    }

    //make sure max result count is a number
    if (!isNumeric(engine.maxResultCount + "")) {
        displayMessage("error", "Maximum Result Count must be numeric.");
        return false;
    }

    return true;
}

function updateEngineCallback(engineID) {
    displayMessage("success", (engineID > 0) ? "Update successful."
            : "Search engine added successfully.");
    var engine = getNewEngine();
    dwr.util.setValues(engine);
    $("search-engine-enabled").checked = engine.enabled;
    $('add-search-descriptor').show();
    $('edit-search-descriptor').hide();
    buildTable();
}

function getNewEngine() {
    return {
        ID:-1,
        shortName:null,
        searchURL:null,
        externalSearchURL:null,
        searchResultContentType:null,
        queryTestTerm:null,
        description:null,
        descriptorURL:"http://",
        iconURL:null,
        username:null,
        password:null,
        enabled:true,
        maxResultCount:20
    };
}

function testEngine(button, engineID) {
    hideMessage();
    displayMessage("info", "Testing ...");
    button.disabled = true;
    OpenSearchSettings.testSearchEngineByID(engineID, {
        callback:function(data) {
            testEngineResults(data, button);
        },
        errorHandler:function(errorString, exception) {
            displayMessage("error", "Test failed." + ((errorString != "") ? ": " + errorString
                    : ""));
            button.disabled = false;
        }
    });
}

function testEngineResults(data, button) {
    if (data) {
        displayMessage("success", "Test succeeded");
    }
    else
    {
        displayMessage("error", "Test failed: No results returned.");
    }
    button.disabled = false;
}

function deleteEngine(engineID) {
    if (confirm("Are you sure ?")) {
        dwr.engine.beginBatch();
        OpenSearchSettings.removeSearchEngineByID(engineID, {
            callback:function() {
                displayMessage("success", "Engine deleted.");
            },
            errorHandler:function(errorString, exception) {
                displayMessage("error", "Delete failed:  " + errorString);
            }});
        buildTable();
        dwr.engine.endBatch();
    }
    showAddView();

}

function showAddView() {
    hideMessage();
    $('add-search-descriptor').show();
    $('edit-search-descriptor').hide();
}

//type is error, info, or success
function displayMessage(type, message) {
    var box = $("opensearch-dialog-box");
    box.show();
    box.className = "jive-" + type + "-box";
    box.innerHTML = message;
}

function hideMessage() {
    $("opensearch-dialog-box").hide();
}

function isContentTypeHTML() {
    var selct = $('edit-search-descriptor-form').elements['searchResultContentType'];
    return (selct.options[selct.selectedIndex].value == 'text/html')
}

function updateExtFieldSelect() {
    var urlf = $('opensearch-external-search-url-field');
    if (isContentTypeHTML()) {
        urlf.hide();
    }
    else
    {
        urlf.show();
    }
}

function trimStr(str) {
    return (str) ? str.replace(/^\s+|\s+$/g, '') : "";
}

function isNumeric(val) {
    return /^\d+$/.test(val + "");
}

//turn off HTML escaping
dwr.util.setEscapeHtml(false);

dwr.engine.setPreHook(function() {
    Element.addClassName(document.body, 'jive-opensearch-progresscursor');
});
dwr.engine.setPostHook(function() {
    Element.removeClassName(document.body, 'jive-opensearch-progresscursor');
});

buildTable();